package org.opensuse.bs.ui.actions;

import java.io.File;
import java.util.Vector;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeViewer;
import org.opensuse.bs.ui.OSC;
import org.opensuse.bs.ui.model.BSModelElement;

public class CheckoutAction extends Action {
	private TreeViewer viewer;
	
	public CheckoutAction(TreeViewer viewer, String name) {
		super(name);
		this.viewer = viewer;
	}
	
	public void run() {
		if(viewer == null) {
			return;
		}
		ITreeSelection node = (ITreeSelection) viewer.getSelection();
		if(node.size() == 0)return;
		final TreePath[] paths = node.getPaths();
		WorkspaceJob checkJob = new WorkspaceJob("Checking out...") {
			public IStatus runInWorkspace(IProgressMonitor monitor) {
				IWorkspace workspace = ResourcesPlugin.getWorkspace();
				IWorkspaceRoot workspaceRoot = workspace.getRoot();
				String root = workspaceRoot.getLocation().toOSString();
				File rootPath = new File(root);
				
				monitor.beginTask("Checkout Elements form Build Service", paths.length);
				try {
					for(TreePath path : paths) {
						if (monitor.isCanceled())
							return Status.CANCEL_STATUS;
						String cmd = "co ";
						for(int i=0;i< path.getSegmentCount();i++) {
							cmd = cmd+" "+((BSModelElement) path.getSegment(i)).getName();
						}
						String element = ((BSModelElement) path.getLastSegment()).getName();
						String project = ((BSModelElement) path.getFirstSegment()).getName();
						monitor.subTask("Checkout \""+element+"\" from \""+project+"\"");
						
						Vector<String> result = OSC.run(cmd, null, rootPath);
						if(result.isEmpty()) {
							monitor.worked(1);
							continue;
						}
						IProject p = workspaceRoot.getProject(project);
						if(!p.exists()) {
							IProjectDescription pd = workspace.newProjectDescription(project);
							pd.setComment("Build Service");
							pd.setNatureIds(new String[]{"org.opensuse.bs.ui.bsprojectnature"});
							p.create(pd, null);
						}
						if(!p.isOpen())
							p.open(null);
						monitor.worked(1);
					}
				}catch(CoreException e) {
					e.printStackTrace();
				}finally {
					monitor.done();
				}
				return Status.OK_STATUS;
			}
		};
		checkJob.schedule();
	}
}
